<?php
if (!defined("_INDEX")) { header("Location: /"); die; }

if (!($user_id = $route->getAdminId()))
	goToPage("/admin/users");

if ($user->getUserId() != 1 && $user->getUserId() != $user_id)
	goToPage("/admin/users");

$errors = array();

if ($route->POST('action') == 'edit')
{
	$login = $route->POST('login');
	$password = $route->POST('password');
	$re_password = $route->POST('re_password');

	$paths = $db->getCell("select `login` from `users` where `login` = '$login' and `user_id` != '$user_id' limit 1");
	if ($paths != null)
		$errors[] = 'Уже существует пользователь с таким логином!';
	
	$query = "update `users` set `login` = '$login'";
	
	if ($password != "")
	{
		if ($password != $re_password)
			$errors[] = "Повтор пароля не совпадает с паролем";
		else
		{
			$salt = rand(1000,9999);
			$password = md5(md5($password).$salt);
			$query .= ",`password`='$password', `salt` = '$salt'";
		}
	}

	$query .= " where `user_id` = '$user_id' limit 1";
	
	if (count($errors) == 0)
	{
		$db->sendQuery($query);
	}
}

$User = $db->getRow("select * from `users` where `user_id` = '$user_id' limit 1");
if ($User == null){
	goToPage("/admin/users");
} else {
	$agent_company = $db->getCell("select `company_id` from `agent` where `user_id` = '".$User['user_id']."'");
}

loadPage("head.php");
?>

<h1>Редактирование пользователя</h1><br /><?php
	if (count($errors) > 0)
		echo "<p class='fail'>".implode("<br />",$errors)."<br /><br /></p>";
	elseif ($route->POST('action') == 'edit')
		echo "<p class='success'>Успешно отредактировано<br /><br /></p>";
?>
<form method='POST' id='edit'>
	<input type='hidden' name='action' value='edit' />
	<table cellpadding='3' cellspacing='5'>
		<tr>
			<td width='170px'>Логин</td>
			<td width='300px'><input type='text' name='login' value='<?php echo $User['login']; ?>' /></td>
		</tr>
		<tr>
			<td>Пароль</td>
			<td><input type='password' name='password' /></td>
		</tr>
		<tr>
			<td>Повтор пароля</td>
			<td><input type='password' name='re_password' /></td>
		</tr>
		<tr>
			<td>Тип</td>
			<td>
				<?php
				switch ($User['type']){
					case "administrator": echo "Администратор"; break;
					case "manager": echo "Менеджер"; break;
					case "agent": echo "Агент"; break;
					default: echo $User['type'];
				}
				?>
			</td>
		</tr>
		<?php
		if ($user->getUserId() == 1 && $User['type'] == "agent"){
			?>
			<tr id="agent_company">
				<td>Компания агента</td>
				<td>
					<select name="company" class="double_short">
						<?php
						$companies = $db->getTable("select `company_id`,`name` from `companies` where `head_office` = '0' order by `name`");
						echo select_create($companies,"company_id","name",$agent_company);
						?>
					</select>
				</td>
			</tr>
			<?php
		}
		?>
		<tr>
			<td colspan='2' align='right'><input type='submit' value='Редактировать' /></td>
		</tr>
	</table>
</form>

<?php loadPage("footer.php"); ?>